<script setup lang='ts' name="member-equity-edit">
import type { FormInstance, FormRules } from 'element-plus'
import type { VxeGridInstance, VxeGridListeners, VxeTableEvents, VxeTableInstance } from 'vxe-table'

import { memberAddRule, memberDeleteRules, memberEditRule, memberGetRuleList, updateEquity, updatePutEquity } from '@fl/api/anjutong'
import ButtonItem from '@fl/components/button-item.vue'
import UpdatedOss from '@fl/components/upLoad-oss.vue'
import { ElCard } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

import { useTable } from './edit-table'

const ruleFormRef = ref()
const router = useRouter()
const route = useRoute()
const formdata = ref<any>({})
formdata.value = route.query
const tableRef = ref<VxeTableInstance<any>>()
const xGrid = ref<VxeGridInstance<any>>()
const { btns, gridOptions } = useTable()
const createAndEdit = ref(false)
const dialogRuleListVisible = ref(false)
const equityOptions = ref([
    {
        color: 'red',
        label: '专属特权',
        value: 0,
    },
    {
        color: 'blue',
        label: '消费折扣',
        value: 1,
    },
])

const formRef = ref()
const form = ref<any>({ code: '', info: '', logo: '', name: '', status: false, type: 0, typeName: '' })
const ruleForm = ref<any>({ info: '', name: '', ratio: '' })

const rules = reactive<FormRules<any>>({
    code: [
        { message: '不能为空', required: true, trigger: 'blur' },
    ],
    info: [
        { message: '不能为空', required: true, trigger: 'blur' },
    ],
    name: [
        { message: '不能为空', required: true, trigger: 'blur' },
    ],
    typeName: [
        {
            message: '请选择',
            required: true,
            trigger: 'change',
        },
    ],
})
const rulesRuleList = reactive<FormRules<any>>({
    info: [
        { message: '不能为空', required: true, trigger: 'blur' },
    ],
    name: [
        { message: '不能为空', required: true, trigger: 'blur' },
    ],
    ratio: [
        { message: '不能为空', required: true, trigger: 'blur' },
    ],
})

async function doSave(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            form.value.status = form.value.status ? 1 : 0 as any
            form.value.type = form.value.typeName
            if (JSON.stringify(formdata.value) === '{}') {
                updateEquity(form.value).then((res: any) => {
                    if (res.code === 200) {
                        ElMessage.success('操作成功')
                        close()
                    }
                    else {
                        ElMessage.error(res.msg)
                    }
                })
            }
            else {
                form.value.type = form.value.type === '专属特权' ? 0 : 1
                updatePutEquity(form.value).then((res: any) => {
                    if (res.code === 200) {
                        ElMessage.success('操作成功')
                        close()
                    }
                    else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
        else {
            ElMessage.error('输入不能为空')

            console.log('error submit!', fields)
        }
    })
}

function close() {
    router.push('/member-center/member/member-equity')
}

async function init() {
    form.value = {
        ...formdata.value,
        status: formdata.value.status === '1',
    }
    getEquityData()
}
init()

const gridEvents: VxeGridListeners<any> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        getEquityData()
    },
}
async function getEquityData() {
    gridOptions.loading = true
    const options = {
        page: gridOptions.pagerConfig.currentPage,
        rightId: form.value.id,
        size: gridOptions.pagerConfig.pageSize,
    }
    memberGetRuleList(options).then((res: any) => {
        gridOptions.pagerConfig.total = res.length ?? 0
        gridOptions.data = res ?? []
        gridOptions.loading = false
    })
}

const selectAllChangeEvent: VxeTableEvents.CheckboxAll<any> = ({ checked }) => {
    const $table = tableRef.value
    if ($table) {
        const records = $table.getCheckboxRecords()
        console.log(checked ? '所有勾选事件' : '所有取消事件', records)
    }
}

const selectChangeEvent: VxeTableEvents.CheckboxChange<any> = ({ checked }) => {
    const $table = tableRef.value
    if ($table) {
        const records = $table.getCheckboxRecords()
        console.log(checked ? '勾选事件' : '取消事件', records)
    }
}
function createRules() {
    dialogRuleListVisible.value = true
    createAndEdit.value = true
    ruleForm.value.name = ''
    ruleForm.value.info = ''
    ruleForm.value.ratio = ''
}
function resetRuleList() {
    ruleForm.value.name = ''
    ruleForm.value.info = ''
    ruleForm.value.ratio = ''
    dialogRuleListVisible.value = false
    getEquityData()
}

async function submitRuleList(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const option = {
                ...ruleForm.value,
                rightId: form.value.id,
            }

            if (createAndEdit.value) {
                memberAddRule(option).then((res) => {
                    console.log(res, 'resresrememberAddRules')

                    getEquityData()
                })
            }
            else {
                memberEditRule(option).then((res) => {
                    console.log(res, 'resresresres')
                    getEquityData()
                })
            }
            dialogRuleListVisible.value = false
        }
        else {
            ElMessage.error('输入不能为空')

            console.log('error submit!', fields)
        }
    })
}

function doAction(item: any, row: any) {
    if (item.value === 'edit') {
        dialogRuleListVisible.value = true
        ruleForm.value = row
        createAndEdit.value = false
    }
    else {
        memberDeleteRules(row.id).then(() => {
            getEquityData()
        })
    }
}

function submitEquity() {
    form.value.status = form.value.status ? 1 : 0 as any
    const flag = form.value.typeName === 0 || form.value.typeName === '专属特权'
    updatePutEquity({
        ...form.value,
        type: flag ? 0 : 1,
        typeName: flag ? '专属特权' : '消费折扣',
    }).then((res: any) => {
        if (res.code === 200) {
            ElMessage.success('操作成功')
            close()
        }
        else {
            ElMessage.error(res.msg)
        }
    })
}
</script>

<template>
    <ElCard>
        <el-form ref="formRef"
                 :model="form"
                 label-width="auto"
                 :rules="rules"
                 style="max-width: 500px"
        >
            <el-form-item label="权益名称"
                          prop="name"
            >
                <el-input v-model="form.name" />
            </el-form-item>

            <!-- <el-form-item label="权益简称"
                          prop="shortName"
            >
                <el-input v-model="form.shortName" />
            </el-form-item> -->
            <el-form-item label="权益类型">
                <el-select v-model="form.typeName"
                           placeholder="请选择"
                           size="large"
                           style="width: 240px"
                >
                    <el-option v-for="item in equityOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="权益编码"
                          prop="code"
            >
                <el-input v-model="form.code" />
            </el-form-item>

            <el-form-item label="权益说明"
                          prop="info"
            >
                <el-input v-model="form.info"
                          type="textarea"
                          clearable
                />
            </el-form-item>

            <el-form-item label="上传图"
                          prop="logo"
            >
                <UpdatedOss v-model="form.logo"
                            :file-list="form.logo"
                />
            </el-form-item>

            <el-form-item label="权益状态"
                          prop="status"
            >
                <el-switch v-model="form.status" />
            </el-form-item>

            <el-form-item v-if="form.type === '0'"
                          flex
                          flex-col
            >
                <el-button type="primary"
                           @click="doSave(formRef)"
                >
                    确定
                </el-button>

                <el-button @click="close">
                    取消
                </el-button>
            </el-form-item>
        </el-form>

        <div v-if="form.type === '1'">
            <div mb-20
                 flex
                 justify-between
                 style="align-items: center;"
            >
                <div>设置规则</div>

                <div>
                    <el-button type="primary"
                               @click="createRules"
                    >
                        新建
                    </el-button>
                </div>
            </div>

            <vxe-grid ref="xGrid"
                      v-bind="gridOptions"
                      v-on="gridEvents"
                      @checkbox-all="selectAllChangeEvent"
                      @checkbox-change="selectChangeEvent"
            >
                >

                <template #operate="{ row }">
                    <ButtonItem :btns="btns"
                                @btn-click="doAction($event, row)"
                    />
                </template>
            </vxe-grid>

            <div mt-20>
                <el-button type="primary"
                           @click="submitEquity"
                >
                    提交
                </el-button>

                <el-button @click="close">
                    返回
                </el-button>
            </div>
        </div>
    </ElCard>

    <el-dialog v-model="dialogRuleListVisible"
               title="新建规则"
               width="800"
               @close="dialogRuleListVisible = false"
    >
        <el-form ref="ruleFormRef"
                 style="max-width: 600px"
                 :model="ruleForm"
                 :rules="rulesRuleList"
                 label-width="auto"
                 label-position="top"
                 class="demo-ruleForm"
                 status-icon
        >
            <el-form-item label="规则名称"
                          prop="name"
            >
                <el-input v-model="ruleForm.name" />
            </el-form-item>

            <el-form-item label="折扣率"
                          prop="ratio"
            >
                <el-input v-model="ruleForm.ratio" />
            </el-form-item>

            <el-form-item label="规则说明"
                          prop="info"
            >
                <el-input v-model="ruleForm.info" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="resetRuleList">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="submitRuleList(ruleFormRef)"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}
</style>
